/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gws;

import gate.Corpus;
import gate.DataStore;
import gate.Document;
import gate.Factory;
import gate.Gate;
import gate.creole.ResourceInstantiationException;
import gate.creole.ir.DefaultIndexDefinition;
import gate.creole.ir.DocumentContentReader;
import gate.creole.ir.IndexException;
import gate.creole.ir.IndexField;
import gate.creole.ir.IndexedCorpus;
import gate.creole.ir.QueryResult;
import gate.creole.ir.QueryResultList;
import gate.creole.ir.Search;
import gate.creole.ir.lucene.LuceneSearch;
import gate.util.Err;
import gate.util.GateException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class GATE {
    //Thu muc goc
    private String ROOT;
    
    //Thư mục lưu trữ index
    private String INDEX_LOCATION;

    //Thư mục lưu trữ datastore
    private String SERIAL_DATASTORE_PATH;
    //NOTE: Thư mục phải trống
    
    private Search search;
    
    private DataStore sds;
    
    public GATE()
    {
        try {
            ROOT = "C:/gate-7-2/GATEWebService/";
            INDEX_LOCATION = ROOT + "index";
            SERIAL_DATASTORE_PATH = "file:///" + ROOT + "datastore";

                // initialize GATE
                Gate.init();
                
                //1. create and open a serial data store
                sds = Factory.createDataStore("gate.persist.SerialDataStore", SERIAL_DATASTORE_PATH);
                sds.open();
                
                //2. create transient corpus
                Corpus corpus =  this.createTestCorpus();
                
                //3. serialize corpus in Serial datastore
                Corpus serialCorpus = (Corpus)sds.adopt(corpus,null);
                
                //4. sync datastore
                sds.sync(serialCorpus);

                //5. index the serialized corpus
                IndexedCorpus indexedCorpus = (IndexedCorpus)serialCorpus;


                //Khởi tạo Index 
                DefaultIndexDefinition did = new DefaultIndexDefinition();
                // Sử dụng kỹ thuật Lucene IR
                //  
                did.setIrEngineClassName(gate.creole.ir.lucene.LuceneIREngine.class.getName());

                //Xác định vị trí index
                did.setIndexLocation(INDEX_LOCATION);

                //Xác định trường index
                did.addIndexField(new IndexField("content", new DocumentContentReader(), false));

                indexedCorpus.setIndexDefinition(did);

                //5.5 ask the IndexManager to create the index (delete it beforehand if already existing)
                indexedCorpus.getIndexManager().deleteIndex();
                indexedCorpus.getIndexManager().createIndex();
                indexedCorpus.getIndexManager().optimizeIndex();
                
                //7.2.  create the proper Search subclass
                //    since we're using the Lucene IR engine, use LuceneSearch
                search = new LuceneSearch();
                //    the Search instance needs to know which corpus to search
                search.setCorpus(indexedCorpus);
        } catch (GateException ex) {
            Logger.getLogger(GATE.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(GATE.class.getName()).log(Level.SEVERE, null, ex);
        }catch (IndexException ex) {
            Logger.getLogger(GATE.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public String timKiem(String query)
    {
        String response = "<p>";
        try
        {
        //Thực thi câu truy vấn
        QueryResultList res = this.search.search(query);
        //Trả về kết quả
        Iterator it = res.getQueryResults();
        //Xem kết quả
        while (it.hasNext()) {
          QueryResult qr = (QueryResult) it.next();
          float score = qr.getScore();
          //
          //  Lấy thông tin về tài liệu liên quan
          Document resultDoc = (Document) this.sds.getLr("gate.corpora.DocumentImpl", qr.getDocumentID());

          response += "<b>" + resultDoc.getName() + "</b><br>";
          response += "<i>Tần suất xuất hiện: " + score + "</i><br>";
          response += resultDoc.getContent() + "<br><br>";
        }
        }
        catch(Exception ex)
        {
            ex.printStackTrace(Err.getPrintWriter());
        }
        response += "</p>";
        return response;
    }
    
    private Corpus createTestCorpus()
    throws MalformedURLException, ResourceInstantiationException {

        Document doc1 = Factory.newDocument(new URL("file:///" + ROOT + "document/1.txt"));
        doc1.setName("Document 1");

        Document doc2 = Factory.newDocument(new URL("file:///" + ROOT + "document/2.txt"));
        doc2.setName("Document 2");

        Document doc3 = Factory.newDocument(new URL("file:///" + ROOT + "document/3.txt"));
        doc3.setName("Document 3");

        Document doc4 = Factory.newDocument(new URL("file:///" + ROOT + "document/4.txt"));
        doc4.setName("Document 4");

        //Tạo 1 corpus với những tài liệu trên
        Corpus result = Factory.newCorpus("test corpus");
        assert result != null;
        result.add(doc1);
        result.add(doc2);
        result.add(doc3);
        result.add(doc4);

        return result;
      }
}
